package com.opNaga.bpmn.actions.io;

import com.opNaga.bpmn.panel.BPMPPanel;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * User: Junyi BEI
 * Date: 20/03/2012
 * Time: 16:07
 */
public class Save extends AbstractAction {
  JTabbedPane tabbedPane;
  JFileChooser chooser;

  public Save(JTabbedPane tabbedPane) {
    this.tabbedPane = tabbedPane;
  }

  public void actionPerformed(ActionEvent e) {
    if(chooser == null) {
      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.addChoosableFileFilter(new FileFilter() {
        public boolean accept(File f) {
          return f.isDirectory() || f.getName().endsWith(".bpmp");
        }

        public String getDescription() {
          return "BPMP Format (.bpmp)";
        }
      });
    }
    if(chooser.showSaveDialog(tabbedPane) == JFileChooser.APPROVE_OPTION) {
      try {
        File selectedFile = chooser.getSelectedFile();
        String path = selectedFile.getPath();
        if(!path.endsWith(".bpmp")) {
          path += ".bpmp";
          selectedFile = new File(path);
        }
        FileOutputStream bpmpOutputStream = new FileOutputStream(selectedFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(bpmpOutputStream);

        int tabNumber = tabbedPane.getTabCount();
        for(int t = 0; t < tabNumber; t++) {
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
          BPMPPanel bpmpPanel = (BPMPPanel) tabbedPane.getComponentAt(t);
          bpmpPanel.saveGraph(byteArrayOutputStream);
          byteArrayOutputStream.close();

          zipOutputStream.putNextEntry(new ZipEntry("BPMP" + t + ".graphml"));
          byte[] buffer = byteArrayOutputStream.toByteArray();
          zipOutputStream.write(buffer);
        }

        zipOutputStream.closeEntry();
        zipOutputStream.close();
      } catch(IOException iE) {
        iE.printStackTrace();
      }
    }
  }
}
